var express = require('express');
var router = express.Router();
var crypto = require('crypto');
var config = require('../config');
/*
*	加密
*/
function encrypto(str){
    var cipher = crypto.createCipher('aes192', config.key);  
    var enc = cipher.update(str,'utf8','hex');  
    enc += cipher.final('hex');  
    return enc;  
}

/*
*	解密
*/
function decrypto(str) {  
    var decipher = crypto.createDecipher('aes192', config.key);  
    var dec = decipher.update(str,'hex','utf8');  
    dec += decipher.final('utf8');
    return dec;  
}

router.get('/login', function(req, res, next){
	if (req.infos) {
		res.redirect('/');
	} else {
		res.render('log', {'title':'user login','user':''})
	}
})

router.post('/login',function(req, res, next){
	try{
		if (req.body.name == '' || req.body.password == '') {
			res.redirect('/log/login')
		} else {

			var log = {
				'name': req.body.name,
				'password': req.body.password
			}
			req.users.find({'name':req.body.name}).toArray(function(err, items){
				if (err) {
					return next(new Error('login error'));
				}
				if (items[0].seal) {
					res.render('prompt',{'title':'you now on blackList','user':''})
				} else {
					if (log.password == items[0].password) {
						res.cookie('recc',items[0]._id,{expires: new Date(Date.now() + 1000*7*24*60*60),path:"/",httpOnly: true});
						res.redirect(301,"/");
					} else {
						res.redirect('/log/login')
					}
				}
			})
		}
	}
	catch(e){
		res.redirect('/log/login')
	}
})

router.get('/outlogin', function(req, res, next){
	res.clearCookie('recc',{path:'/'});
	res.redirect(301,"/")
})

router.get('/reg', function(req, res, next){
	res.render('reg', {'title':'welcome reg','user':''})
})

router.post('/reg', function(req, res, next){
	var insert = {
		'name':req.body.name,
		'password':req.body.password,
		'email':req.body.email,
		'LV':0,
		'headImgUrl':'/images/defaultHead.png',
		'motto':"",
		'regTime':new Date().getTime()
	}
	req.users.insert(insert, function(err, result){
		if (err) {
			return next(new Error('insert error'));
		}
		res.redirect('/log/login')
	})
})

router.get('/ajaxUsername', function(req, res, next){
	req.users.find({'name':req.query.selectName}).toArray(function(err, items){
		if (err) {
			return next(new Error('reg error'));
		} else {
			if (items==null || items=='') {
				res.json({'status':true})
			} else {
				res.json({'status':false})
			}
		}
	})
})

module.exports = router;